package net.wang.zk.demo;


import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.ZooKeeper;
import org.junit.Test;

import java.io.IOException;

@Slf4j
public class ZKSessionWatcherTest {

    private static final String zkServerPath = "localhost:2181";  //单个节点连接

    //public static final String zkServerPath = "localhost:2181,localhost:2182,localhost:2183";//伪分布式集群连接
    public static final Integer timeout = 5000;

    @Test
    public void testSessionWatcher() throws InterruptedException, IOException {


        ZooKeeper zooKeeper = new ZooKeeper(zkServerPath, timeout, event -> log.info("====>watched : {}", event));
        Thread.sleep(1000);
        log.info("===>客户端已连接");

        long sessionId = zooKeeper.getSessionId();//连接上才会从0变成其他数字
        log.info("===> ssid = {}", "0x" + Long.toHexString(sessionId));


        byte[] sessionPasswd = zooKeeper.getSessionPasswd();
        zooKeeper.close();

        log.info("===>客户端连接状态：{}", zooKeeper.getState());
        log.info("===> sessionId = {}", "0x" + Long.toHexString(zooKeeper.getSessionId()));
        Thread.sleep(200);

        log.info("===>会话开始重新连接");
        ZooKeeper keeper = new ZooKeeper(zkServerPath, timeout, event -> log.info("====>watched : {}", event), sessionId, sessionPasswd);
        log.info("===>重新连接状态:{}", keeper.getState());
        Thread.sleep(1000);

        log.info("===>sessionId = {}", "0x" + Long.toHexString(keeper.getSessionId()));

        keeper.close();
    }


}


